/*************************************************************************
	> File Name: main.c
	> Author: gyl
	> Mail: gyldeyx@qq.com
	> Created Time: Fri 01 Jan 2021 09:10:23 PM CST
 ************************************************************************/

#include "log.h"
#include "server.h"
#include <unistd.h>
#include <signal.h>
#include <iostream>
#include <linux/limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void closeServer(int signo) {
    std::cout << "bye" << std::endl;
    exit(1);
}

int main(int argc, char **argv) {
    //初始化日志系统
    if (!(Log::get_instance()->init())) {
        std::cout << "log init failed!" << std::endl;
        return -1;
    }

    int iPort = -1;
    int opt = 0;
    while ((opt = getopt(argc, argv, "dp:")) != -1) {
        switch (opt) {
            case 'd':
                //守护进程
                {
                    pid_t pid;

                    pid = fork();
                    if (pid == -1) 
                        return -1;
                    else if (pid != 0)
                        exit(EXIT_SUCCESS);

                    //子进程中
                    if (setsid() == -1)
                        return -1;
                    if (chdir("/") == -1)
                        return -1;

                    for (int i = 0; i < NR_OPEN; i++) {
                        close(i);
                    }
    
                    //重定向标准输入到 /dev/null，因为此时open返回的fd 是 0，以下同理
                    open("/dev/null", O_RDONLY);
                    open("/dev/null", O_RDWR);
                    open("/dev/null", O_RDWR);
                }
                break;
            case 'p':
                //端口号
                iPort = atoi(optarg);
                break;
            default:
                fprintf(stderr, "Usage: %s [-d] [-p port]\n", argv[0]);
                exit(-1);
        }
    }

    //接收ctrl c中断信号，输出信息，结束程序
    signal(SIGINT, closeServer);

    Server server;
    server.init(iPort);
    server.start();
    return 0;
}
